﻿namespace AC.ExtendedRenderer.Toolkit.Utils
{
    using System;
    using System.Runtime.CompilerServices;
    using System.Windows.Forms;

    internal class SubClass : NativeWindow
    {
        private bool IsSubClassed;

        public event SubClassWndProcEventHandler SubClassedWndProc;

        public SubClass(IntPtr Handle, bool _SubClass)
        {
            base.AssignHandle(Handle);
            this.IsSubClassed = _SubClass;
        }

        public void CallDefaultWndProc(ref Message m)
        {
            base.WndProc(ref m);
        }

        public int HiWord(int Number)
        {
            return ((Number >> 0x10) & 0xffff);
        }

        public int LoWord(int Number)
        {
            return (Number & 0xffff);
        }

        public int MakeLong(int LoWord, int HiWord)
        {
            return ((HiWord << 0x10) | (LoWord & 0xffff));
        }

        public IntPtr MakeLParam(int LoWord, int HiWord)
        {
            return (IntPtr) ((HiWord << 0x10) | (LoWord & 0xffff));
        }

        private int OnSubClassedWndProc(ref Message m)
        {
            if (this.SubClassedWndProc != null)
            {
                return this.SubClassedWndProc(ref m);
            }
            return 0;
        }

        protected override void WndProc(ref Message m)
        {
            if (!this.IsSubClassed || (this.OnSubClassedWndProc(ref m) == 0))
            {
                base.WndProc(ref m);
            }
        }

        public bool SubClassed
        {
            get
            {
                return this.IsSubClassed;
            }
            set
            {
                this.IsSubClassed = value;
            }
        }

        public delegate int SubClassWndProcEventHandler(ref Message m);
    }
}

